/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.controller.evaluation.prepare.course;

import cn.ac.nercis.pes.common.constant.common.BaseConstants;
import cn.ac.nercis.pes.common.constant.evaluation.EvaluationModule;
import cn.ac.nercis.pes.common.constant.project.FinishState;
import cn.ac.nercis.pes.common.utils.RichTextUtil;
import cn.ac.nercis.pes.community.component.controls.EvalPlanControl;
import cn.ac.nercis.pes.community.component.dialog.*;
import cn.ac.nercis.pes.community.component.photo.ThumbnailControl;
import cn.ac.nercis.pes.community.constant.SaveMethod;
import cn.ac.nercis.pes.community.controller.base.GlobalEventHandle;
import cn.ac.nercis.pes.community.controller.base.InitEvalDataLoad;
import cn.ac.nercis.pes.community.controller.evaluation.prepare.PrepareController;
import cn.ac.nercis.pes.community.manager.RealTimeSaveManager;
import cn.ac.nercis.pes.community.utils.*;
import cn.ac.nercis.pes.community.views.evaluation.prepare.PrepareView;
import cn.ac.nercis.pes.model.dto.evaluation.content.BusinessConditionDTO;
import cn.ac.nercis.pes.service.evaluation.EvaluationContentService;
import cn.ac.nercis.pes.service.evaluation.EvaluationProcessService;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import lombok.extern.slf4j.Slf4j;

import java.net.URL;
import java.util.ResourceBundle;
import java.util.concurrent.CompletableFuture;

/**
 * 测评过程管理控制器
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public class EvalProcessController implements Initializable, GlobalEventHandle, InitEvalDataLoad {

    @FXML
    private StackPane page;
    @FXML
    private Button saveButton;
    @FXML
    private Button tmpSaveButton;

    @FXML
    private EvalPlanControl planSheet;

    private final EvaluationProcessService processService;

    private String currentSystemId;

    public EvalProcessController() {
        this.processService = SpringUtils.getBean(EvaluationProcessService.class);
    }


    @Override
    public void initialize(URL location, ResourceBundle resources) {
        saveButton.setGraphic(IconUtils.getGlyph("save-button-icon","btn-icon"));
        tmpSaveButton.setGraphic(IconUtils.getGlyph("temp-save-button-icon","btn-icon"));
        planSheet.setRealTimeSave(this::realTimeSave);
        GuiStore.applyQuickSave(this.page,this::onGlobalSave);
    }

    @Override
    public void initializeData(String systemId){
        LogUtils.info(log, "初始化测评过程信息...");
        this.currentSystemId = systemId;
        loadEvaluationState();
    }

    @Override
    public void onGlobalSave() {
        LogUtils.info(log, "执行快捷保存操作...");
        saveEvalProcess(false,false);
    }

    @FXML
    public void onTmpSave(){
        LogUtils.info(log, "执行暂存操作...");
        saveEvalProcess(false,false);
    }

    @FXML
    public void onFinishSave(){
        LogUtils.info(log, "执行保存操作...");
        saveEvalProcess(false,true);
    }

    public void realTimeSave(){
        LogUtils.info(log, "执行即时保存操作...");
        saveEvalProcess(true,false);
    }

    private void loadEvaluationState() {
        LogUtils.info(log, "加载测评过程信息...");
        LogUtils.info(log, "请求数据：{}", this.currentSystemId);
        CompletableFuture.supplyAsync(() -> this.processService.getEvaluationStage(this.currentSystemId))
                .thenAccept(res -> Platform.runLater(() -> planSheet.loadContent(res)))
                .exceptionally((ex) -> {
                    log.error("加载测评过程信息出错!", ex);
                    return null;
                });
    }

    private void saveEvalProcess(boolean isRealTime ,boolean finish) {
        if (finish) {
            if (!planSheet.validContent(this.page)) {
                return;
            }
        }
        var evaluationStageDTO = planSheet.getData();
        LogUtils.info(log, "保存测评过程信息...");
        LogUtils.record(log, "请求数据：{}", evaluationStageDTO);
        CompletableFuture.supplyAsync(() -> this.processService.saveEvaluationState(evaluationStageDTO))
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        if(!isRealTime){
                            AppUtils.showMessageDialog("保存成功",MessageType.SUCCESS,this.page);
                        }
                        refreshFinishProcess(finish);
                    } else {
                        if(isRealTime){
                            log.error("即时保存失败：{}",res.getMsg());
                            LogUtils.record(log,"保存数据：{}",evaluationStageDTO);
                        }else{
                            AppUtils.showMessageDialog(res.getMsg(),MessageType.FAIL,this.page);
                        }
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("保存测评过程信息出错!", ex);
                    return null;
                });
    }

    private void refreshFinishProcess(boolean finish){
        var prepareView = AppStore.getEvaluationView(this.currentSystemId, PrepareView.class);
        if(prepareView.getController() instanceof PrepareController controller){
            controller.setEvalProcess(EvaluationModule.COURSE_PROCESS, finish ? FinishState.FINISH:FinishState.INCOMPLETE);
        }
    }

}